package com.aiti.lulian.controller.promotion;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.annotates.AddGroup;
import com.aiti.lulian.annotates.EditGroup;
import com.aiti.lulian.dto.CardLeaveInformationDto;
import com.aiti.lulian.entity.crad.promotion.CardLeaveInformation;
import com.aiti.lulian.entity.crad.promotion.CardPromotion;
import com.aiti.lulian.entity.crad.promotion.CardPromotionSub;
import com.aiti.lulian.service.ICardLeaveInformationService;
import com.aiti.lulian.service.ICardPromotionService;
import com.aiti.lulian.service.ICardPromotionSubService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/card/leave")
public class CardLeaveInformationController extends WebController<CardLeaveInformation> {

    private final ICardLeaveInformationService baseService;

    private final ICardPromotionService promotionService;

    private final ICardPromotionSubService subService;

    public CardLeaveInformationController(ICardLeaveInformationService baseService,
                                          ICardPromotionService promotionService,
                                          ICardPromotionSubService subService) {
        this.baseService = baseService;
        this.promotionService = promotionService;
        this.subService = subService;
    }

    /**
     * 用户在小程序端的留资
     * @param leaveInformation 用户填写的信息
     * @return 结果
     */
    @PostMapping("/addCardLeaveInformation")
    public Message addCardLeaveInformation(@Validated(value = {AddGroup.class}) @RequestBody CardLeaveInformation leaveInformation) {
        leaveInformation.setBaseId(IdUtil.simpleUUID());
        leaveInformation.setBaseCreateTime(DateUtil.date());
        baseService.save(leaveInformation);
        return Message.success();
    }

    /**
     * 查询留资所有未交缴的数据 列表
     * @return
     */
    @GetMapping("/queryCardLeaveList")
    public Message queryCardLeaveList() {
        LambdaQueryWrapper<CardLeaveInformation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CardLeaveInformation::getStatus,"0");
        lqw.isNotNull(CardLeaveInformation::getPromotionCode);
        lqw.select(CardLeaveInformation::getBaseId,CardLeaveInformation::getCompanyName);
        List<CardLeaveInformation> list = baseService.list(lqw);
        return Message.success(list);
    }

    /**
     * 填写购买记录
     * @param leaveInformation 参数
     * @return 结果
     */
    @PostMapping("/payFees")
    @Transactional(rollbackFor = Exception.class)
    public Message payFees(@Validated(value = {EditGroup.class}) @RequestBody CardLeaveInformation leaveInformation){
        if(StringUtils.isBlank(leaveInformation.getPayVersion())){
            return Message.fail("购买版本不能为空");
        }
        if(leaveInformation.getPayAmount() == null){
            return Message.fail("购买金额不能为空");
        }
        CardLeaveInformation information = baseService.getById(leaveInformation.getBaseId());
        if(information == null){
            throw new RuntimeException("没有找到这个Id对应的数据");
        }

        String userId = findUserId();

        LambdaUpdateWrapper<CardLeaveInformation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CardLeaveInformation::getPayVersion,leaveInformation.getPayVersion());
        updateWrapper.set(CardLeaveInformation::getPayAmount,leaveInformation.getPayAmount());
        updateWrapper.set(CardLeaveInformation::getStatus,"1");
        updateWrapper.set(CardLeaveInformation::getPayTime,DateUtil.date());
        updateWrapper.set(CardLeaveInformation::getPayOperUserId,userId);
        updateWrapper.eq(CardLeaveInformation::getBaseId,leaveInformation.getBaseId());
        baseService.update(updateWrapper);

        //获取到推广码
        String promotionCode = information.getPromotionCode();
        if(StringUtils.isBlank(promotionCode)){
            throw new RuntimeException("没有找到推广码");
        }

        //根据推广码更新推广人和关联用户的数据
        CardPromotionSub subPromotion = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("promotion_code", promotionCode).isNull("delete_time"));
        if(subPromotion == null){
            CardPromotion cardPromotion = promotionService.getOne(new QueryWrapper<CardPromotion>().eq("promotion_code", promotionCode).isNull("delete_time"));
            if(cardPromotion != null){
                //这里需要已有的成交金额加上当前传入的成交金额
                BigDecimal transactionAmount = cardPromotion.getTransactionAmount();
                transactionAmount = transactionAmount.add(leaveInformation.getPayAmount());

                //计算比例
                Integer ratio = cardPromotion.getRatio() == null ? 0 : cardPromotion.getRatio();
                BigDecimal ratioBigDecimal = BigDecimal.valueOf(ratio);

                ratioBigDecimal = ratioBigDecimal.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                BigDecimal cumulativeGain = leaveInformation.getPayAmount().multiply(ratioBigDecimal);
                BigDecimal dbCumulativeGin = cardPromotion.getCumulativeGain();
                dbCumulativeGin =  dbCumulativeGin.add(cumulativeGain);


                UpdateWrapper<CardPromotion> cardPromotionUpdateWrapper = new UpdateWrapper<>();
                cardPromotionUpdateWrapper.eq("base_id",cardPromotion.getBaseId());
                cardPromotionUpdateWrapper.isNull("delete_time");
                cardPromotionUpdateWrapper.set("pay_count",cardPromotion.getPayCount() + 1);
                cardPromotionUpdateWrapper.set("transaction_amount",transactionAmount);
                cardPromotionUpdateWrapper.set("cumulative_gain",dbCumulativeGin);
                promotionService.update(cardPromotionUpdateWrapper);
            }else{
//                File touch = new File("./log.txt");
//                if(!FileUtil.exist("./log.txt")){
//                    touch = FileUtil.touch("./log.txt");
//                }
//                FileAppender appender = new FileAppender(touch, 1, true);
//                String jl = String.format("时间：%s ==> ID:%s,所持有的推广码【%s】已被删除，不计入收益，用户开通版本【%s】，支付金额【%s】",DateUtil.now(),leaveInformation.getBaseId(),promotionCode,leaveInformation.getPayVersion(),leaveInformation.getPayAmount().toString());
//                appender.append(jl);
//                appender.flush();

                CardPromotionSub deleteSub = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("promotion_code", promotionCode));
                if(deleteSub != null){
                    //推广人ID  外键Id
                    String masterId = deleteSub.getPkId();
                    //缴费次数
                    Long payCount = deleteSub.getPayCount();
                    //缴费金额
                    BigDecimal transactionAmount = deleteSub.getTransactionAmount();

                    //新的缴费金额
                    transactionAmount = transactionAmount.add(leaveInformation.getPayAmount());
                    payCount = payCount + 1L;

                    //子表中的主键
                    String baseId = deleteSub.getBaseId();


                    //更新主键中的内容
                    UpdateWrapper<CardPromotion> masterUpdate = new UpdateWrapper<>();

                    //查询主表中已存在的数据
//                    CardPromotion masterPromotion = promotionService.getById(masterId);
                    CardPromotion masterPromotion = promotionService.getOne(new QueryWrapper<CardPromotion>().eq("base_id",masterId).isNull("delete_time"));
                    if(masterPromotion != null){
                        //新的缴费总数
                        BigDecimal masterDbTransactionAmount = masterPromotion.getTransactionAmount();
                        masterDbTransactionAmount = masterDbTransactionAmount.add(leaveInformation.getPayAmount());

                        //新的比例
                        Integer ratio = masterPromotion.getRatio() == null ? 0 : masterPromotion.getRatio();
                        BigDecimal ratioBigDecimal = BigDecimal.valueOf(ratio);
                        ratioBigDecimal = ratioBigDecimal.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

                        BigDecimal cumulativeGain = masterPromotion.getCumulativeGain();
                        BigDecimal masterCumulativeGain = leaveInformation.getPayAmount().multiply(ratioBigDecimal);
                        masterCumulativeGain = masterCumulativeGain.add(cumulativeGain);

                        //新的缴费次数
                        Long masterDbPayCount = masterPromotion.getPayCount();
                        masterDbPayCount = masterDbPayCount + 1L;

                        masterUpdate.eq("base_id",masterId);
                        masterUpdate.isNull("delete_time");
                        masterUpdate.set("pay_count",masterDbPayCount);
                        masterUpdate.set("transaction_amount",masterDbTransactionAmount);
                        masterUpdate.set("cumulative_gain",masterCumulativeGain);
                        promotionService.update(masterUpdate);

                        UpdateWrapper<CardPromotionSub> cardPromotionUpdateWrapper = new UpdateWrapper<>();
                        cardPromotionUpdateWrapper.eq("base_id",baseId);
                        cardPromotionUpdateWrapper.isNull("delete_time");
                        cardPromotionUpdateWrapper.set("pay_count",payCount);
                        cardPromotionUpdateWrapper.set("transaction_amount",transactionAmount);
                        subService.update(cardPromotionUpdateWrapper);
                    }
                }
            }
        }else{
            //推广人ID  外键Id
            String masterId = subPromotion.getPkId();
            //缴费次数
            Long payCount = subPromotion.getPayCount();
            //缴费金额
            BigDecimal transactionAmount = subPromotion.getTransactionAmount();

            //新的缴费金额
            transactionAmount = transactionAmount.add(leaveInformation.getPayAmount());
            payCount = payCount + 1L;

            //子表中的主键
            String baseId = subPromotion.getBaseId();
            UpdateWrapper<CardPromotionSub> cardPromotionUpdateWrapper = new UpdateWrapper<>();
            cardPromotionUpdateWrapper.eq("base_id",baseId);
            cardPromotionUpdateWrapper.isNull("delete_time");
            cardPromotionUpdateWrapper.set("pay_count",payCount);
            cardPromotionUpdateWrapper.set("transaction_amount",transactionAmount);
            subService.update(cardPromotionUpdateWrapper);

            //更新主键中的内容
            UpdateWrapper<CardPromotion> masterUpdate = new UpdateWrapper<>();

            //查询主表中已存在的数据
            CardPromotion masterPromotion = promotionService.getById(masterId);

            //新的缴费总数
            BigDecimal masterDbTransactionAmount = masterPromotion.getTransactionAmount();
            masterDbTransactionAmount = masterDbTransactionAmount.add(leaveInformation.getPayAmount());

            //新的比例
            Integer ratio = masterPromotion.getRatio() == null ? 0 : masterPromotion.getRatio();
            BigDecimal ratioBigDecimal = BigDecimal.valueOf(ratio);
            ratioBigDecimal = ratioBigDecimal.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

            BigDecimal masterCumulativeGain = leaveInformation.getPayAmount().multiply(ratioBigDecimal);

            BigDecimal cumulativeGain = masterPromotion.getCumulativeGain();
            cumulativeGain = cumulativeGain.add(masterCumulativeGain);

            //新的缴费次数
            Long masterDbPayCount = masterPromotion.getPayCount();
            masterDbPayCount = masterDbPayCount + 1L;

            masterUpdate.eq("base_id",masterId);
            masterUpdate.isNull("delete_time");
            masterUpdate.set("pay_count",masterDbPayCount);
            masterUpdate.set("transaction_amount",masterDbTransactionAmount);
            masterUpdate.set("cumulative_gain",cumulativeGain);

            promotionService.update(masterUpdate);
        }
        return Message.success();
    }

    /**
     * 查询留资列表 分页
     * @param dto 参数
     * @return 结果
     */
    @GetMapping("/getCardLeaveList")
    public Message getCardLeaveList(CardLeaveInformationDto dto){
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        Page<CardLeaveInformation> cardLeaveInformationPage = startPage(pageNum, pageSize);

        LambdaQueryWrapper<CardLeaveInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(dto.getCompanyName()),CardLeaveInformation::getCompanyName,dto.getCompanyName());
        queryWrapper.like(StringUtils.isNotBlank(dto.getLinkMan()),CardLeaveInformation::getLinkMan,dto.getLinkMan());
        queryWrapper.eq(StringUtils.isNotBlank(dto.getLinkPhone()),CardLeaveInformation::getLinkPhone,dto.getLinkPhone());
        queryWrapper.eq(StringUtils.isNotBlank(dto.getPayVersion()),CardLeaveInformation::getPayVersion,dto.getPayVersion());
        queryWrapper.eq(StringUtils.isNotBlank(dto.getStatus()),CardLeaveInformation::getStatus,dto.getStatus());
        queryWrapper.orderByDesc(CardLeaveInformation::getBaseCreateTime);

        Page<CardLeaveInformation> page = baseService.page(cardLeaveInformationPage,queryWrapper);
        return Message.success(page);
    }

    /**
     * 判断当前账号是否已提交过留资（用于资质认定模块）
     */
    @GetMapping("/isSubmitted")
    public Message isSubmitted(@RequestParam("userId") String userId){
        int count = baseService.count(new LambdaQueryWrapper<CardLeaveInformation>().eq(CardLeaveInformation::getCreator, userId).eq(CardLeaveInformation::getSource, "2"));
        if (count > 0) {
            return Message.success(true);
        } else {
            return Message.success(false);
        }
    }

    /**
     * 新版名片小程序：判断当前账号是否已提交过留资（用于资质认定模块）
     */
    @GetMapping("/isSubmittedNew")
    public Message isSubmittedNew(@RequestParam("userId") String userId){
        Map<String, Boolean> resultMap = new HashMap<>();
        boolean sdzzYszt = false;
        boolean sdzzPprd = false;
        int count1 = baseService.count(new LambdaQueryWrapper<CardLeaveInformation>().eq(CardLeaveInformation::getCreator, userId).eq(CardLeaveInformation::getSource, "2").eq(CardLeaveInformation::getDescContent, "“山东制造·云上展厅”资质认定"));
        if (count1 > 0) {
            sdzzYszt = true;
        }
        int count2 = baseService.count(new LambdaQueryWrapper<CardLeaveInformation>().eq(CardLeaveInformation::getCreator, userId).eq(CardLeaveInformation::getSource, "2").eq(CardLeaveInformation::getDescContent, "“山东制造·品牌认定”资质认定"));
        if (count2 > 0) {
            sdzzPprd = true;
        }
        resultMap.put("sdzzYszt", sdzzYszt);
        resultMap.put("sdzzPprd", sdzzPprd);
        return Message.success(resultMap);
    }
}
